import { defineStore } from 'pinia'
import { ref } from 'vue'
import { statisticsAPI, inspectionAPI } from '@/api/modules'


/**
 * 仪表盘数据管理
 * 管理仪表盘的统计数据、图表数据等
 */
export const useDashboardStore = defineStore('dashboard', () => {
  // 状态
  const statistics = ref({
    totalLines: 0,
    todayInspections: 0,
    pendingDefects: 0,
    completionRate: 0
  })

  const systemStatus = ref({
    status: 'normal',
    lastUpdate: '刚刚'
  })

  const inspectionProgress = ref({
    labels: [],
    data: []
  })

  const defectDistribution = ref({
    labels: [],
    data: [],
    colors: ['#10B981', '#F59E0B', '#EF4444']
  })


  /**
   * 获取统计数据
   */
  const fetchStatistics = async () => {
    try {
      const response = await statisticsAPI.getDashboardStats()
      
      if (response.code === 0) {
        const data = response.data
        
        // 更新统计数据
        statistics.value = {
          totalLines: data.taskStats?.total || 0,
          todayInspections: data.taskStats?.completed || 0,
          pendingDefects: data.defectStats?.total || 0,
          completionRate: data.taskStats?.completionRate || 0
        }
        
        // 更新系统状态
        systemStatus.value = {
          status: 'normal',
          lastUpdate: '刚刚'
        }
        
        return statistics.value
      } else {
        throw new Error(response.message || '获取统计数据失败')
      }
    } catch (error) {
      console.error('获取统计数据失败:', error)
      throw error
    }
  }

  /**
   * 获取系统状态
   */
  const fetchSystemStatus = async () => {
    try {
      const response = await statisticsAPI.getPersonnelStats()
      
      if (response.code === 0) {
        const data = response.data
        
        systemStatus.value = {
          status: 'normal',
          lastUpdate: '刚刚'
        }
        
        return systemStatus.value
      } else {
        throw new Error(response.message || '获取系统状态失败')
      }
    } catch (error) {
      console.error('获取系统状态失败:', error)
      throw error
    }
  }

  /**
   * 获取巡检进度数据
   */
  const fetchInspectionProgress = async () => {
    try {
      const response = await statisticsAPI.getTaskStats()
      if (response.code === 0) {
        const data = response.data
        
        // 处理趋势数据
        if (data.trend && data.trend.length > 0) {
          // 只取最近7天的数据用于显示
          const recentTrend = data.trend.slice(-7)
          
          const labels = recentTrend.map(item => {
            const date = new Date(item.date)
            return `${date.getMonth() + 1}/${date.getDate()}`
          })
          const values = recentTrend.map(item => item.count)
          
          inspectionProgress.value = {
            labels,
            data: values
          }
        } else {
          // 如果后端没有趋势数据，使用示例数据
          inspectionProgress.value = {
            labels: ['1日', '5日', '10日', '15日', '20日', '25日', '30日'],
            data: [3, 5, 8, 12, 15, 18, 20]
          }
        }
        
        return inspectionProgress.value
      } else {
        throw new Error(response.message || '获取巡检进度失败')
      }
    } catch (error) {
      console.error('获取巡检进度失败:', error)
      // 如果API调用失败，使用示例数据
      inspectionProgress.value = {
        labels: ['1日', '5日', '10日', '15日', '20日', '25日', '30日'],
        data: [3, 5, 8, 12, 15, 18, 20]
      }
      return inspectionProgress.value
    }
  }

  /**
   * 获取缺陷分布数据
   */
  const fetchDefectDistribution = async () => {
    try {
      const response = await statisticsAPI.getDefectStats()
      
      if (response.code === 0) {
        const data = response.data
        
        // 处理缺陷等级分布
        if (data.byLevel) {
          const labels = Object.keys(data.byLevel).map(key => {
            const levelMap = {
              'general': '一般',
              'serious': '严重',
              'urgent': '紧急'
            }
            return levelMap[key] || key
          })
          const values = Object.values(data.byLevel)
          
          defectDistribution.value = {
            labels,
            data: values,
            colors: ['#10B981', '#F59E0B', '#EF4444']
          }
        }
        
        return defectDistribution.value
      } else {
        throw new Error(response.message || '获取缺陷分布失败')
      }
    } catch (error) {
      console.error('获取缺陷分布失败:', error)
      throw error
    }
  }



  /**
   * 刷新所有数据
   */
  const refreshAllData = async () => {
    try {
      await Promise.all([
        fetchStatistics(),
        fetchSystemStatus(),
        fetchInspectionProgress(),
        fetchDefectDistribution()
      ])
    } catch (error) {
      console.error('刷新数据失败:', error)
      throw error
    }
  }

  return {
    // 状态
    statistics,
    systemStatus,
    inspectionProgress,
    defectDistribution,
    
    // 方法
    fetchStatistics,
    fetchSystemStatus,
    fetchInspectionProgress,
    fetchDefectDistribution,
    refreshAllData
  }
})
